package com.guigu.qingcheng.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.guigu.qingcheng.excption.GuliException;
import com.guigu.qingcheng.mapper.*;
import com.guigu.qingcheng.pojo.*;
import com.guigu.qingcheng.pojo.vo.CategoryReportVo;
import com.guigu.qingcheng.pojo.dto.CaiFenDinDan;
import com.guigu.qingcheng.pojo.vo.CaiFenVo;
import com.guigu.qingcheng.service.TbOrderItemService;
import com.guigu.qingcheng.utils.IdWorker;
import com.guigu.qingcheng.utils.PageUtil;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
*
* @author Jiang
* @date 2020/07/31
*/
@Service
public class TbOrderItemServiceImpl implements TbOrderItemService {

    @Autowired(required = false)
    private TbOrderItemMapper tbOrderItemMapper;

    @Autowired(required = false)
    private TbOrderMapper tbOrderMapper;

    @Autowired(required = false)
    private TbPreferentialMapper tbPreferentialMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired(required = false)
    private TbOrderLogMapper tbOrderLogMapper;


    public  void addLog(TbOrder order,String beizhu){
        // 记录订单日志
        TbOrderLog log=new TbOrderLog();
        log.setId(idWorker.nextId()+""); // id
        log.setOperater("system"); // 操作员 暂时设为系统
        log.setOperateTime(new Date()); // 操作时间
        log.setOrderId(order.getId()); // 订单id
        log.setOrderStatus(order.getOrderStatus()); // 订单状态
        log.setPayStatus(order.getPayStatus()); // 付款状态
        log.setConsignStatus(order.getConsignStatus()); // 发货状态
        log.setRemarks(beizhu); // 备注
        tbOrderLogMapper.insertSelective(log);
    }


    @Override
    public Map findTotalSalesonweek(CategoryReportVo categoryReportVo) {
        return tbOrderItemMapper.findTotalSalesonweek(categoryReportVo);
    }

    /**
     * 查询销售总额
     * @param localDate
     * @return
     */
    @Override
    public Map findTotalSales(LocalDate localDate) {
        return tbOrderItemMapper.findTotalSales(localDate);
    }

    @Override
    public List<TbOrderItem> queryAll() {
        List<TbOrderItem> tbOrderItem = tbOrderItemMapper.selectAll();
            return tbOrderItem;
    }

    @Override
    public PageUtil<TbOrderItem> findListAll(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        Page<TbOrderItem> pages = (Page<TbOrderItem>) tbOrderItemMapper.selectAll();
        PageUtil<TbOrderItem> pageUtil=new PageUtil<>();
        pageUtil.setRows(pages.getResult());
        pageUtil.setTotal(pages.getTotal());
        return pageUtil;
    }


    @Override
    public PageUtil<TbOrderItem> pageQueryByAll(Integer pageNum, Integer pageSize, TbOrderItem tbOrderItem) {

        Example example=new Example(TbOrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        // TODO 待实现 重新实现判断参数

        //if(!StringUtils.isEmpty(brand.getId())){
        //    criteria.andEqualTo("id",brand.getId());
        //}
        //if(!StringUtils.isEmpty(brand.getName())){
        //   criteria.andLike("name","%"+brand.getName()+"%");
        //}
        PageHelper.startPage(pageNum,pageSize);
        Page<TbOrderItem> pages = (Page<TbOrderItem>) tbOrderItemMapper.selectByExample(example);
        PageUtil<TbOrderItem> pageUtil=new PageUtil<>();
        pageUtil.setRows(pages.getResult());
        pageUtil.setTotal(pages.getTotal());
        return pageUtil;
     }


    @Override
    public boolean saveTbOrderItem(TbOrderItem tbOrderItem) {
        int insert = tbOrderItemMapper.insert(tbOrderItem);
        if(insert>0){
            return true;
        }
        return false;
    }

    @Override
    public boolean updateTbOrderItem(TbOrderItem tbOrderItem) {
        int i = tbOrderItemMapper.updateByPrimaryKeySelective(tbOrderItem);
        if(i>0){
            return true;
        }
        return false;
    }


    @Override
    public boolean deleteById(Integer id) {
        int i = tbOrderItemMapper.deleteByPrimaryKey(id);
        if(i>0){
            return true;
        }
        return false;
    }

    @Override
    public TbOrderItem findById(Integer id) {
        TbOrderItem tbOrderItem = tbOrderItemMapper.selectByPrimaryKey(id);
        return tbOrderItem;
    }


    @Transactional
    @Override
    public void caiFen(List<CaiFenVo> caiFenVos) {
        // 根据list中订单明细的id获取到订单的数据
        TbOrderItem tbOrderItem1 = tbOrderItemMapper.selectByPrimaryKey(caiFenVos.get(0).getId());
        TbOrder order= tbOrderMapper.selectByPrimaryKey(tbOrderItem1.getOrderId());
        //创建新的订单对象 用于产生新的订单 并赋初始值
        TbOrder order1=new TbOrder();
        BeanUtils.copyProperties(order,order1);
        order1.setId(idWorker.nextId()+"");
        order1.setCreateTime(new Date()); // 订单创建时间
        order1.setUpdateTime(new Date()); // 订单更新时间
        tbOrderMapper.insertSelective(order1);

        // 设置变量 num，money 用于保存拆分后的订单数量和金额
        int num=0;
        int money=0;
        int fee=0;
        // 循环list 判断拆分数量是否为零  是否等于总数量
        for (CaiFenVo c : caiFenVos) {
            if(c.getSum()>0){
                TbOrderItem tbOrderItem = tbOrderItemMapper.selectByPrimaryKey(c.getId());
                // 判断拆分数量是否大于订单数量
                if(c.getSum()>tbOrderItem.getNum()){
                    throw new GuliException(20001,"拆分数量大于订单数量");
                }
                if(tbOrderItem.getNum()==c.getSum()){
                    throw new GuliException(20001,"拆分数量不能等于总数量,拆分取消!");
                }

                // 创建订单明细对象 用于产生新的订单明细
                TbOrderItem tbOrderItem2=new TbOrderItem();

                BeanUtils.copyProperties(tbOrderItem,tbOrderItem2);
                tbOrderItem2.setId(idWorker.nextId()+"");
                tbOrderItem2.setOrderId(order1.getId());
                tbOrderItem2.setNum(tbOrderItem.getNum()-c.getSum());
                tbOrderItem2.setMoney(tbOrderItem2.getPrice()*tbOrderItem2.getNum());
                tbOrderItem2.setPayMoney(tbOrderItem2.getMoney());

                tbOrderItem2.setWeight((tbOrderItem.getWeight()/tbOrderItem.getNum())*tbOrderItem2.getNum());

                tbOrderItemMapper.insertSelective(tbOrderItem2);

                num=num+tbOrderItem2.getNum();
                money=money+tbOrderItem2.getMoney();

                // 修改原来的订单明细
                // 数量=原来的数量-分掉的数量
                tbOrderItem.setNum(tbOrderItem.getNum()-tbOrderItem2.getNum());
                tbOrderItem.setMoney(tbOrderItem.getMoney()-tbOrderItem2.getMoney());
                tbOrderItem.setPayMoney(tbOrderItem.getMoney());
                tbOrderItem.setWeight(tbOrderItem.getWeight()-tbOrderItem2.getWeight());
                tbOrderItemMapper.updateByPrimaryKeySelective(tbOrderItem);
            }
        }

        // 修改新增订单的数量
        order1.setTotalNum(num);
        order1.setTotalMoney(money);
        tbOrderMapper.updateByPrimaryKeySelective(order1);

        // 修改原来订单的数量
        order.setTotalNum(order.getTotalNum()-num);
        order.setTotalMoney(order.getTotalMoney()-money);
        tbOrderMapper.updateByPrimaryKeySelective(order);



        // 邮费

        addLog(order,"拆分订单:"+order1.getId());
    }

    @Override
    public List<CaiFenDinDan> queryByOrderIdGoods(String orderId) {
        List<CaiFenDinDan> tbOrderItems = tbOrderItemMapper.queryByspId(orderId);
        return tbOrderItems;
    }

    @Transactional
    @Override
    public void addGoodsOrder(TbOrderItem tbOrderItem) {
        tbOrderItem.setId(idWorker.nextId()+"");
        tbOrderItem.setPostFee(8); // 运费
        tbOrderItem.setIsReturn("0"); //是否退货
        tbOrderItem.setPayMoney(tbOrderItem.getMoney());
        // 查询当前的订单
        TbOrder order = tbOrderMapper.selectByPrimaryKey(tbOrderItem.getOrderId());

        // 查询有没有优惠金额
        Example example=new Example(TbPreferential.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andGreaterThan("endTime",new Date());
        List<Integer> list=new ArrayList<>();
        list.add(tbOrderItem.getCategoryId1());
        list.add(tbOrderItem.getCategoryId2());
        list.add(tbOrderItem.getCategoryId3());
        criteria.andIn("categoryId",list);
        criteria.andGreaterThanOrEqualTo("buyMoney",tbOrderItem.getMoney());
        criteria.andLessThan("startTime",new Date());
        List<TbPreferential> tbPreferentials = tbPreferentialMapper.selectByExample(example);

        if(tbPreferentials.size()>0){
            TbPreferential tbPreferential = tbPreferentials.get(0);
            // 减去优惠金额
            tbOrderItem.setPayMoney(tbOrderItem.getPayMoney()-tbPreferential.getPreMoney());
            order.setPreMoney(order.getPreMoney()+tbPreferential.getPreMoney()); // 订单优惠金额
        }

        order.setTotalNum(order.getTotalNum()+tbOrderItem.getNum()); // 总数量
        order.setTotalMoney(order.getTotalMoney()+tbOrderItem.getMoney()); // 总金额
        order.setPostFee(order.getPostFee()+tbOrderItem.getPostFee()); //邮费
        order.setPayMoney(order.getPayMoney()+tbOrderItem.getPayMoney()); //实付金额

        tbOrderItemMapper.insertSelective(tbOrderItem);

        tbOrderMapper.updateByPrimaryKeySelective(order);


        addLog(order,"修改商品信息,新增商品明细:"+tbOrderItem.getId());

    }

    @Override
    public List<TbOrderItem> getOrderItem(String orderId) {
        Example example=new Example(TbOrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId",orderId);
        List<TbOrderItem> tbOrderItems = tbOrderItemMapper.selectByExample(example);
        return tbOrderItems;
    }

    @Override
    public List<Map> findHost() {
        List<Map> maps = tbOrderItemMapper.hostCommodities();
        return maps;
    }

    @Override
    public List<Map> pricelower() {
        List<Map> maps = tbOrderItemMapper.lessPrice();
        return maps;
    }

    @Override
    public List<Map> Commoditieseqs() {
        List<Map> commodities = tbOrderItemMapper.newCommodities();
        return commodities;
    }


}
